var express = require('express');
var router = express.Router();
var db = require("../util/DataBase.js");

var rankScore = require("../system/article_rank_score.js");

var articleService = require("../service/article.js");
var messageService = require("../service/message.js");
var replyService = require("../service/reply.js");
var searchService = require("../service/search.js");

router.post('/create', function(req, res, next) {
  var body = req.body;

  var values = [
    body.articleId,
    body.content,
    body.answer,
    req.session.user.id * 1
  ];

  db.query("INSERT INTO `reply` (`article_id`, `content`, `answer`, `user_id`) VALUES (?, ?, ?, ?)", values, function(err, results) {
      if(err)
      {
        res.json(null, -1, "发表讨论失败")
      }
      else
      {
        if(body.answer) {
          articleService.adjustRank(body.articleId, rankScore.USER_ANSWER);
          messageService.fire("answer", body.articleId + "_" + results.insertId, {
            nickname: req.session.user.nickname,
            content: body.content
          });
        } else {
          articleService.adjustRank(body.articleId, rankScore.USER_REPLY);
          messageService.fire("reply", body.articleId + "_" + results.insertId, {
            nickname: req.session.user.nickname,
            content: body.content
          });
        }
        searchService.addReply(body.articleId, {
          id: results.insertId,
          content: body.content
        })
        res.json({
          id: results.insertId
        });
      }

  });

});

router.post('/good/:id', function(req, res, next) {

  replyService.isUserReplyGood(
    req.params.id,
    req.session.user.id,
    function (isGood) {

      if(isGood) {
        db.query("DELETE FROM reply_good WHERE `reply_id` = ? AND `user_id` = ?", [
          req.params.id,
          req.session.user.id
        ], function (err, goodResults) {
          if(err) {
            res.json(null, -1, "取消点赞失败");
          } else {
            replyService.goodCount(req.params.id, function (count) {

              replyService.getArticleId(req.params.id, function (articleId) {
                articleService.adjustRank(articleId, rankScore.USER_ANSWER_GOOD * -1);
              });

              res.json({
                userGood: false,
                count: count
              });
            }, function () {
              res.json(null, -1, "获取点赞数失败");
            });
          }
        })
      } else {
        db.query("INSERT INTO `reply_good` (`reply_id`, `user_id`) VALUES (?, ?)", [
          req.params.id,
          req.session.user.id
        ], function (err, goodResults) {
          if(err) {
            res.json(null, -1, "点赞失败");
          } else {
            replyService.goodCount(req.params.id, function (count) {

              replyService.getArticleId(req.params.id, function (articleId) {
                articleService.adjustRank(articleId, rankScore.USER_ANSWER_GOOD);
              });

              res.json({
                userGood: true,
                count: count
              });
            }, function () {
              res.json(null, -1, "获取点赞数失败");
            });
          }
        })
      }

    },
    function () {
      res.json(null, -1, "获取当前点赞状态失败")
    }
  );

});

router.get('/:id', function(req, res, next) {

  var values = [
    req.params.id * 1
  ];

  db.query("SELECT `id`, `article_id`, `content`, `answer`, `user_id` FROM `reply` WHERE `id` = ?", values, function(err, results) {

      if(err)
      {
          res.json(null, -1, "获取评论失败");
          return;
      }

      if(results.length <= 0) {
        res.json([]);
        return;
      }

      var userLoaded = 0;

      for(var i = 0, l = results.length; i < l; ++ i) {
        var reply = results[i];
        (function (_reply) {
          db.query("SELECT `id`, `nickname`, `avatar_url` FROM `user` WHERE `id` = ?", [_reply.user_id], function (err, userResults) {

            db.query("SELECT count(`id`) as reply_count FROM `reply` WHERE `reply_id` = ?", [_reply.id], function (err, replyCountResults) {

              _reply.user = userResults[0];
              _reply.reply_count = replyCountResults[0].reply_count;

              replyService.goodCount(_reply.id, function (count) {

                _reply.reply_good_count = count;

                replyService.isUserReplyGood(
                  _reply.id,
                  req.session.user.id,
                  function (isGood) {

                    _reply.good_trigged = isGood;

                    if(++ userLoaded == l) {
                      res.json(results[0]);
                    }

                  },
                  function () {
                    res.json(null, -1, "获取点赞状态失败");
                  }
                );

              }, function () {
                res.json(null, -1, "获取点赞数失败");
              });

            });

          });
        })(reply);
      }

  });

});

router.get('/list/:articleId', function(req, res, next) {

  var values = [
    req.params.articleId * 1,
    req.query.startId * 1,
    req.query.len * 1
  ];

  db.query("SELECT `id`, `article_id`, `content`, `answer`, `user_id` FROM `reply` WHERE `article_id` = ? AND `reply_id` is NULL AND `id` " + ( req.query.sort === "asc" ? "<" : ">") + " ? ORDER BY `id` DESC LIMIT ?", values, function(err, results) {

      if(err)
      {
          res.json(null, -1, "获取评论失败");
          return;
      }

      if(results.length <= 0) {
        res.json([]);
        return;
      }

      var userLoaded = 0;

      for(var i = 0, l = results.length; i < l; ++ i) {
        var reply = results[i];
        (function (_reply) {
          db.query("SELECT `id`, `nickname`, `avatar_url` FROM `user` WHERE `id` = ?", [_reply.user_id], function (err, userResults) {

            db.query("SELECT count(`id`) as reply_count FROM `reply` WHERE `reply_id` = ?", [_reply.id], function (err, replyCountResults) {

              _reply.user = userResults[0];
              _reply.reply_count = replyCountResults[0].reply_count;

              replyService.goodCount(_reply.id, function (count) {

                _reply.reply_good_count = count;

                replyService.isUserReplyGood(
                  _reply.id,
                  req.session.user.id,
                  function (isGood) {

                    _reply.good_trigged = isGood;

                    if(++ userLoaded == l) {
                      res.json(results);
                    }

                  },
                  function () {
                    res.json(null, -1, "获取点赞状态失败");
                  }
                );

              }, function () {
                res.json(null, -1, "获取点赞数失败");
              });

            });
          });
        })(reply);
      }

  });

});

module.exports = router;
